package com.angenela.imageshare.activity;

import  android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.StrictMode;
import android.text.InputType;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.angenela.imageshare.MainActivity;
import com.angenela.imageshare.R;
import com.angenela.imageshare.dto.UserDTO;
import com.angenela.imageshare.pojo.User;
import com.angenela.imageshare.util.JsonUtil;

import java.io.IOException;

import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class LoginActivity extends AppCompatActivity {

    private static final String LOGIN_URL = "http://122.9.152.182:8080/user/login";
    private boolean pwdSwitch = false;
    private TextView username;
    private TextView password;
    private CheckBox remember;
    private TextView registry;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        // 不想在子线程进行网络请求，所以添加以下的判断
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

        username = findViewById(R.id.email);
        password = findViewById(R.id.password);
        remember = findViewById(R.id.remember_me);
        registry = findViewById(R.id.sign_up);

        registry.setOnClickListener((view) -> {
            Intent intent = new Intent(this, RegistryActivity.class);
            startActivity(intent);
        });

        //----------------------------- 以下为获取报错的用户信息
        Resources resources = getResources();
        String spFileNameKey = resources.getString(R.string.shared_preferences_file_name);
        String emailKey = resources.getString(R.string.login_account_username);
        String passwordKey = resources.getString(R.string.login_account_password);
        String rememberKey = resources.getString(R.string.login_remember_password);

        SharedPreferences sharedPreferences =
                getSharedPreferences(spFileNameKey, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();

        String emailVal = sharedPreferences.getString(emailKey, "");
        String passwordVal = sharedPreferences.getString(passwordKey, "");
        boolean rememberVal = sharedPreferences.getBoolean(rememberKey, false);

        username.setText(emailVal);
        password.setText(passwordVal);
        remember.setChecked(rememberVal);

        //-----------------------------------------------
    }

    // 登录逻辑
    public void login(View view) throws IOException {
        String username = this.username.getText().toString();
        String password = this.password.getText().toString();

        // 发送信息到后端进行验证
        UserDTO result = loginCheck(username, password);
        User user = result.getData();

        // 显示弹窗
        if (!result.getCode().equals(200)) {
            AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
            dialogBuilder.setMessage(result.getMessage());
            dialogBuilder.setTitle("提示");
            dialogBuilder.setPositiveButton("确定", null);
            AlertDialog alertdialog = dialogBuilder.create();
            alertdialog.show();
            return;
        }

        Resources resources = getResources();
        String spFileNameKey = resources.getString(R.string.shared_preferences_file_name);
        String usernameKey = resources.getString(R.string.login_account_username);
        String idKey = resources.getString(R.string.login_account_id);
        String avatarKey = resources.getString(R.string.login_account_avatar);
        String createTimeKey = resources.getString(R.string.login_account_create_time);
        String passwordKey = resources.getString(R.string.login_account_password);
        String rememberKey = resources.getString(R.string.login_remember_password);

        SharedPreferences sharedPreferences =
                getSharedPreferences(spFileNameKey, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();

        if (remember.isChecked()) {
            // 保存用户信息
            editor.putString(usernameKey, user.getUsername());
            editor.putString(passwordKey, user.getPassword());
            editor.putInt(idKey, user.getId());
            editor.putString(createTimeKey, user.getCreateTime());
            editor.putString(avatarKey, user.getAvatar());
            editor.putBoolean(rememberKey, true);
        } else {
            editor.remove(usernameKey);
            editor.remove(passwordKey);
            editor.remove(rememberKey);
            editor.remove(createTimeKey);
            editor.remove(avatarKey);
            editor.remove(idKey);
        }

        editor.apply();

        // 转到MainActivity
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
    }

    // 进行网络请求，验证用户名和密码是否有误
    public UserDTO loginCheck(String username, String password) throws IOException {
        OkHttpClient okHttpClient = new OkHttpClient();

        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("username", username)
                .addFormDataPart("password", password)
                .build();

        Request request = new Request.Builder()
                .url(LOGIN_URL)
                .post(requestBody)
                .build();

        Response response = okHttpClient.newCall(request).execute();

        UserDTO result = JsonUtil.jsonToObject(UserDTO.class, response.body().string());

        return result;
    }

    public void pwdSwitch(View view) {
        EditText text = findViewById(R.id.password);
        ImageView img = (ImageView) view;
        if (pwdSwitch == false) {
            pwdSwitch = true;
            img.setImageResource(R.drawable.ic_baseline_visibility_24);
            text.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
        } else {
            pwdSwitch = false;
            img.setImageResource(R.drawable.ic_baseline_visibility_off_24);
            text.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD | InputType.TYPE_CLASS_TEXT);
        }
    }
}
